﻿/**
 * The Content class is a container for overviewing all content
*/
dynamic class Content extends MovieClip {
	
	// constants
	var padding:Number = 10;
	
	// variables
	var element_id:Number;
	var column_count:Number;
	var content_array:Array;
	var current_focused_element:Object;
	var current_focused_text:Object;
	var save_lv:LoadVars;
	
	/**
	 * Content() initialises the Content class
	*/
	function Content() {
		
		// Call initialise
		initialise();
		
		// Add a background
		this.attachMovie("content_background", "background_mc", this.getNextHighestDepth(), {
			_visible: true,
			_alpha: 100,
			useHandCursor: false
		});
		
		// Make background clickable to remove focus
		this.background_mc.onRelease = function() {
			_parent.removeElementFocus();
		}
	}
	
	/**
	 * initialise() initialises or resets the variables
	*/
	function initialise():Void {
		
		// Set vars
		this.element_id = 0;
		this.column_count = 0;
		this.content_array = new Array();
		this.current_focused_element = null;
		
		// Reset scrollbar
		_root.content_scrollpane.vPosition = 0;
	}
	
	/**
	 * reset() resets the content
	*/
	function reset():Void {
		
		// Remove all elements
		this.deleteAllElements();
		
		// Initialise variables
		this.initialise();
	}
	
	/**
	 * saveContent() saves the content
	*/
	function saveContent():Void {
		
		// Prepare content for saving
		addOutput("Saving...");
		
		// Instantiate loadvars
		this.save_lv = new LoadVars();
		
		// Get content
		this.save_lv.content = getContentSource();
		
		// Get ID
		this.save_lv.page = _root.PAGE_ID;
		
		// Get Type
		this.save_lv.type = _root.PAGE_TYPE;
		
		/**
		 * onLoad of save LoadVars object
		*/
		this.save_lv.onLoad = function(success:Boolean):Void {
			if (success && this.savesuccess == "true") {
				
				addOutput("Page saved successfully", "confirm");
				
				// Load data
				loadData();
			} else {
				addOutput("An error occured while saving: " + this.error, "error");
			}
		}
		
		this.save_lv.sendAndLoad(_root.HOST_URL + _root.SAVE_DATA_URL, this.save_lv, "post");
	}
	
	
	
	/*************************************

function saveContent() {

	// prepare content for saving
	saveContent_lv.id = _root.getPageId();
	saveContent_lv.title = _root.title_txt.text;
	saveContent_lv.content = getContentSource();
	
	// Replace HTML tags
	var strContent = getContentSource();
	strContent.replace("<", "&gt;");
	strContent.replace(">", "&lt;");

	// Check saving correct page
	if (saveContent_lv.title != editContent_lv.title) {
		_root.refreshHierarchyTreeScrollPane()
	}
	
	// Show message
	_root.displayMessage("Saving " + saveContent_lv.title + ", please wait...");

	// Send content
	saveContent_lv.sendAndLoad("content_update.php", saveContent_lv, "POST");
	//getURL("content_update.php", "_blank", "POST");
}



saveContent_lv.onLoad = function(success) {
	
	// If both load vars and PHP actions worked OK...
	if (success && this.serverSuccess) {

		// Display message
		_root.displayMessage(saveContent_lv.title+" saved successfully");
		
	// Else if something went wrong
	} else {
		
		// If problem with load vars
		if (!success) {
			
			_root.displayError("An error occured, could not load PHP page");
			
		} else {
			
			_root.displayError("Unable to save " + saveContent_lv.title + ", error: " + this.errorMsg);
		}
	}
};
	*************************************/
	
	/**
	 * loadContent() loads existing content into the Content object
	 *
	 * @param content_string is a string of XML
	*/
	function loadContent(content_string:String):Void {
		
		// Reset settings
		removeElementFocus();
		removeContentElements();
		initialise();

		// Parse into XML
		var content_xml:XML = new XML(content_string);
		
		// Reference movieclip
		var element_mc:MovieClip;
		
		// Load content
		if (content_xml.firstChild.nodeName == "content") {
			
			// For each column
			for (var column_node:XMLNode = content_xml.firstChild.firstChild; column_node != null; column_node = column_node.nextSibling) {

				// Add a column element
				element_mc = addColumnElement();
				
				// Cycle through tables
				for (var table_node:XMLNode = column_node.firstChild; table_node != null; table_node = table_node.nextSibling) {
					
					// Cycle through elements within table
					for (var element_node = table_node.firstChild; element_node != null; element_node=element_node.nextSibling) {
						
						// Handle different element types
						switch (element_node.nodeName) {
							
							// Plain text
							case "text":
							
								// Add an element
								element_mc = addTextElement();
								
								// Set the source
								element_mc.setSource(element_node);
							
								break;
								
							// HTML Text
							case "HTMLTextbox":
							
								// Add element
								element_mc = addHTMLTextboxElement();
								
								// Set the source
								element_mc.setSource(element_node);
							
								break;
								
							// Image
							case "image":
							
								// Add element
								element_mc = addImageElement();
								
								// Set the source
								element_mc.setSource(element_node);
								
								// Load the image
								element_mc.loadImage();
							
								break;
						}
					}
				}
			}
		} else {
			
			// Output
			addOutput("An error occured during content load", "error");
		}
		
		// Ensure at least one column exists, and make column button active/inactive
		switch (column_count) {
			case 0:
				
				// Ensure columns button is off
				_root.setControlButtonMode("insert_columns_mc", false);
				
				// Add an empty column element
				addColumnElement();
				
				break;
				
			case 1:
			
				// Ensure columns button is off
				_root.setControlButtonMode("insert_columns_mc", false);
				
				break;
				
			case 2:
			
				// Ensure columns button is on
				_root.setControlButtonMode("insert_columns_mc", true);
				
				break;
			
		}
		
		// Draw
		this.drawLayout();
	}
	
	
	/**
	 * addColumnElement() adds a new column element
	*/
	function addColumnElement() {
		
		// ID of element
		var column_id:String;
		
		// Check that another column is allowed
		if (this.column_count > 1) {
			
			// Error
			addOutput("addColumnElement(): Sorry, page can contain a maximum of 2 columns.", "error");
			
			// Fail
			return false;
			
		} else {

			// Increment column count
			this.column_count++;			
			
			// Increment element count
			this.element_id++;
			
			// Create Unique ID for column
			column_id = "column_" + element_id;
			
			// Attach a movie
			var column_mc:MovieClip = this.attachMovie("Column", column_id, this.getNextHighestDepth(), {
				_visible: false,
				column_number: this.column_count
			});
			
			// Add element
			addElement(column_mc);
			
			// Return element
			return column_mc;
		}
	}
	
	/**
	 * addImageElement() adds an image element
	*/
	function addImageElement():MovieClip {
		
		// Unique ID of element
		var image_id:String;
		
		// Increment element count
		element_id++;
		
		// Generate Unique ID
		image_id = "image_" + element_id;
		
		// Attach MovieClip
		var image_mc:MovieClip = this.attachMovie("Image", image_id, this.getNextHighestDepth(), {
			_visible: false
		});
		
		// Add to array
		addElement(image_mc);

		// Return
		return image_mc;
	}
	
	/**
	 * addTextElement() adds a text element
	*/
	function addTextElement():MovieClip {
		
		// Unique ID of element
		var text_id:String;
		
		// Increment element count
		element_id++;
		
		// Generate Unique ID
		text_id = "text_" + element_id;
		
		// Attach MovieClip
		var text_mc:MovieClip = this.attachMovie("Text", text_id, this.getNextHighestDepth(), {
			_visible:false
		});
		
		// Add to array
		addElement(text_mc);
		
		// Draw
		drawLayout();
		
		// Return
		return text_mc;
	}
	
	/**
	 * addHTMLTextboxElement() adds a HTML Textbox element
	*/
	function addHTMLTextboxElement():MovieClip {
		
		// Unique ID of element
		var htmltext_id:String;
		
		// Increment element count
		element_id++;
		
		// Generate Unique ID
		htmltext_id = "htmltextbox_" + element_id;
		
		// Attach MovieClip
		var htmltextbox_mc = this.attachMovie("HTMLTextbox", htmltext_id, this.getNextHighestDepth(), {
			_visible:false
		});
		
		// Add to array
		addElement(htmltextbox_mc);
		
		// Draw
		drawLayout();
		
		// Return
		return htmltextbox_mc;
	}
	
	/**
	 * addElement() adds an element
	 *
	 * @param element_mc is the movieclip being added
	*/
	function addElement(element_mc:MovieClip) {
		
		// Position of new element
		var index = -1;
		
		// Check whether another element is currently focused
		if (this.current_focused_element != null) {
			
			// Find element index position
			for (var i = 0; i < this.content_array.length; i++) {
				
				// If element matches
				if (this.content_array[i] == this.current_focused_element) {
					
					// Retain index
					index = i;
					
					// Finished
					break;
				}
			}
		}
		
		// If no element was selected, append new element to end
		if (index == -1) {
			
			// Attach element to array at end
			this.content_array.push(element_mc);
			
		} else {
			
			// Otherwise attach element above selected element
			this.content_array.splice(index, 0, element_mc);
		}
	}
	
	/**
	 * getContentSource() gets the source for the entire content area
	 *
	 * @return a string of the content source
	*/
	function getContentSource():String {
		
		// Element MovieClip
		var element_mc:MovieClip;
		
		// Source String
		var content_source = "";
		
		// For each content element (except the first, which is the first column)
		for (var i:Number = 1; i < this.content_array.length; i++) {
			
			// Get the source
			content_source += this.content_array[i].getSource();
		}
		
		// Add column brackets
		content_source = "<column class=\"column1\">" + content_source + "</column>";
		
		// Process the display type
		content_source = this.processDisplayType(content_source);
		
		// Return
		return content_source;
	}
	
	/**
	 * processDisplayType() processes the display types
	 *
	 * @param content_source is the incoming source to be parsed
	 *
	 * @return the content source with display types handled
	*/
	function processDisplayType(content_source:String):String {
		
		// Convert to XML
		var content_xml:XML = new XML(content_source);
		
		// Create Output XML
		var new_content_xml:XML = new XML("<content />");
		
		// Is a table container open?
		var table_open:Boolean;
		
		// For each column
		for (var column_xml:XMLNode = content_xml.firstChild; column_xml != null; column_xml=column_xml.nextSibling) {
			
			// Table is not open at start of column
			table_open = false;
			
			// Copy <column> to new XML (but not any children)
			new_content_xml.firstChild.appendChild(column_xml.cloneNode(false));
			
			// Iterate through elements of column
			for (var element_xml:XMLNode = column_xml.firstChild; element_xml != null; element_xml=element_xml.nextSibling) {
				
				// If a table is already open, add this item to it
				if (table_open == true) {

					// Append a copy of this element
					new_content_xml.firstChild.lastChild.lastChild.appendChild(element_xml.cloneNode(true));

				} else {
					
					// Create table node
					var table_element_xml:XMLNode = new_content_xml.createElement("table");
					
					// Move a copy of element node to inside table
					table_element_xml.appendChild(element_xml.cloneNode(true));
					
					// Add table to end of content
					new_content_xml.firstChild.lastChild.appendChild(table_element_xml);
				}
				
				// Determine if table remains open
				if (element_xml.attributes.display == "inline") {
					table_open = true;
				} else {
					table_open = false;
				}
			}
		}

		// Finished, so return
		return new_content_xml.toString();
	}

	/**
	 * toggleColumns() toggles the columns mode
	*/
	function toggleColumns():Void {
		
		// If there are two column elements, delete the last one
		if (this.column_count == 2) {
			deleteLastColumnElement();
			
		// Otherwise add a new one
		} else {
			addColumnElement();
		}
	}	

	/**
	 * deleteLastColumnElement() deletes the last column
	*/
	function deleteLastColumnElement():Void {
		
		// For each element
		for (var i = this.content_array.length - 1; i >= 0; i--) {
			
			// If element is a column...
			if (this.content_array[i].isColumn()) {
				
				// Decrement column count
				this.column_count--;
				
				// Delete the column
				this.deleteElement(this.content_array[i]);
				
				// End
				break;
			}
		}
	}	
	
	/**
	 * drawLayout() draws the content
	 *
	 * @return false if the content is not finished loading, or true if everything went OK
	*/
	function drawLayout():Boolean {
		
		// Array of columns
		var column_array:Array = new Array();
		
		// Current Column Element
		var current_column_mc:MovieClip;
		
		// Current Element
		var current_element_mc:MovieClip;
		
		// Ensure loading is finished
		if (!this.contentIsLoaded()) {
			return false;
		}
		
		// Process columns
		for (var i = 0; i < this.content_array.length; i++) {
			
			// Get current element
			current_element_mc = this.content_array[i];			
			
			// If element is a column, process it
			if (current_element_mc.isColumn()) {

				// Store current column
				current_column_mc = current_element_mc;
				
				// Reset appearance
				current_column_mc.resetLayout();
				
				// Add to column array
				column_array.push(current_column_mc);
				
			} else {
				
				// Add element to current column
				current_column_mc.addElement(current_element_mc);
			}
		}
		
		// Get X position of first column
		var column_x = this.padding;
		
		// Draw content columns
		for (var i = 0; i < column_array.length; i++) {
			
			// Get current column
			current_column_mc = column_array[i];
			
			// Position column
			current_column_mc.setColumnX(column_x);
			
			// Draw contents of column
			current_column_mc.drawLayout();
			
			// Increase column X by width of current column (plus padding)
			column_x += current_column_mc.getRenderWidth() + this.padding;
		}
		
		// Resize background to fit
		this.background_mc._width = 0;
		this.background_mc._height = 0;
		
		// Check if width is at least the size of the scrollpane
		this.background_mc._width = (this._width + 10 > this._parent.width) ? this._width + 10 : this._parent.width;
		this.background_mc._height = (this._height + 10 > this._parent.height) ? this._height + 10 : this._parent.height;
		
		// Update scrollbars
		_root.redrawContentArea();
		
		// OK
		return true;
	}	
	
	/**
	 * contentIsLoaded() returns whether the content has finished loading
	*/
	function contentIsLoaded():Boolean {
		
		// For each element
		for (var i:Number = 0; i < this.content_array.length; i++) {
			
			// If it's an image, check if it is loaded
			if (this.content_array[i].isImage() && !this.content_array[i].isLoaded()) {
				
				// If not, fail
				return false;
			}
		}
		
		// OK
		return true;
	}
	
	/**
	 * moveElementUp() moves an element up
	 *
	 * @param element_mc is the element to move up
	*/
	function moveElementUp(element_mc:MovieClip):Void {
		
		// For each element
		for (var i:Number = 0; i < this.content_array.length; i++) {
			
			// If found the passed element
			if (this.content_array[i] == element_mc) {
				
				// If element is not the second (first being the column)
				if (i > 1) {
					
					// Store previous element in this location
					this.content_array[i] = this.content_array[i-1];
					
					// Store passed element in previous element's location
					this.content_array[i-1] = element_mc;
					
					// End
					break;
				}
			}
		}
		
		// Redraw
		this.drawLayout();
	}
	
	/**
	 * moveElementDown() moves an element down
	 *
	 * @param element_mc is the element to move
	*/
	function moveElementDown(element_mc:MovieClip):Void {
		
		// For each element
		for (var i:Number = 0; i < this.content_array.length; i++) {
			
			// If found the passed element
			if (this.content_array[i] == element_mc) {
				
				// If not at the end of the array
				if (i < this.content_array.length-1) {
					
					// Move next element into this location
					this.content_array[i] = this.content_array[i+1];
					
					// Place passed element in next location
					this.content_array[i+1] = element_mc;
					
					// End
					break;
				}
			}
		}
		
		// Redraw
		this.drawLayout();
	}

	/**
	 * deleteAllElements() removes all elements from the content
	*/
	function deleteAllElements():Void {
		
		// Remove all movieclips
		for (var i:Number = 0; i < this.content_array.length; i++) {
			this.content_array[i].removeMovieClip();
		}		
		
		// Redraw
		this.drawLayout();
	}
	
	/**
	 * deleteElement() deletes an element
	 *
	 * @param element_mc is the element to delete
	*/
	function deleteElement(element_mc:MovieClip):Void {
		
		// Output
		addOutput("Element '" + element_mc._name + "' deleted.");
		
		// For each element
		for (var i:Number = 0; i < this.content_array.length; i++) {
			
			// If element matches
			if (this.content_array[i] == element_mc) {
				
				// Remove from array
				this.content_array.splice(i, 1);
				
				// Remove movieclip
				element_mc.removeMovieClip();
				
				break;
			}
		}
		
		// Redraw
		this.drawLayout();
	}
	
	
	
	

	function getImageProperty(strImageProperties_array, strProperty) {		
		
		for (var i = 0; i<strImageProperties_array.length; i++) {
			if (strImageProperties_array[i].indexOf(strProperty) == 0) {
				return strImageProperties_array[i].split(":")[1];
			}
		}
		
		return "";
	}
	
	function setElementFocus(objElement) {
		this.current_focused_element.blurElement();
		this.current_focused_element = objElement;
		this.current_focused_element.focusElement();
	}
	
	function getElementFocus() {
		return this.current_focused_element;
	}
		
	function removeElementFocus() {
		this.current_focused_element.blurElement();
		this.current_focused_element = null;
	}
	
	function setCurrentTextFocus(objText) {
		this.current_focused_text = objText;
	}
	
	function getCurrentTextFocus() {
		return this.current_focused_text;
	}

	function removeContentElements() {
		for (var i = 0; i<this.content_array.length; i++) {
			this.content_array[i].removeMovieClip();
		}
	}
		
	function getColumnWidth(intColumnNum) {
		return (intColumnNum == 1)?(580*0.6):(580*0.4);
	}
}